package com.guaju.yueshangLife.fragment;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.activity.CategoryActivity;
import com.guaju.yueshangLife.activity.MainActivity;
import com.guaju.yueshangLife.adapter.CateTabAdapter;
import com.guaju.yueshangLife.adapter.MyFragmentPagerAdapter;
import com.guaju.yueshangLife.base.BaseFragment;
import com.guaju.yueshangLife.bean.HomeTotal;
import com.guaju.yueshangLife.databinding.FragmentHomeBinding;
import com.guaju.yueshangLife.fragment.home.RecommendFragment;
import com.guaju.yueshangLife.fragment.home.TotalGoodsFragment;
import com.guaju.yueshangLife.net.ApiEntity;
import com.guaju.yueshangLife.recyclerView.divider.DividerGridItemDecoration;
import com.guaju.yueshangLife.utils.ScreenUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by guaju on 2018/9/20.
 */

public class HomeFragment extends BaseFragment {

    FragmentHomeBinding binding;
    private ArrayList<String> mTitleList = new ArrayList<>(2);
    private ArrayList<Fragment> mFragments = new ArrayList<>(2);
    private boolean mIsPrepared;
    private boolean mIsFirst = true;
    private List<TabBean> tabBeanList;
    private ArrayList<CateTabAdapter.CateTab> cateTabs = new ArrayList<>();
    public HomeTotal.DataBean data;
    private MainActivity mainActivity;
    private boolean isTotalMode = false;
    private CategoryActivity categoryActivity;
    PopupWindow window;
    private ArrayList<LinearLayout> linearLayouts = new ArrayList<>();
    private ArrayList<RadioButton> radioButtons = new ArrayList<>();


    @Override
    public int setContent() {
        return R.layout.fragment_home;
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        binding = (FragmentHomeBinding) bindingView;
        EventBus.getDefault().register(this);
        // 准备就绪
        mIsPrepared = true;
        loadData();
        showLoading();

        /**
         * 注意使用的是：getChildFragmentManager，
         * 这样setOffscreenPageLimit()就可以添加上，保留相邻3个实例，切换时不会卡
         * 但会内存溢出，在显示时加载数据
         */

        showContentView();
        if (getActivity() instanceof MainActivity) {
            mainActivity = (MainActivity) getActivity();
        } else if (getActivity() instanceof CategoryActivity) {
            categoryActivity = (CategoryActivity) getActivity();
        }

        // item点击跳转
//        initRxBus();
    }

    //设置tablayout的tab宽度包裹内容
    public void reflex(final TabLayout tabLayout) {
        //了解源码得知 线的宽度是根据 tabView的宽度来设置的
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到tabLayout的mTabStrip属性
                    Field mTabStripField = tabLayout.getClass().getDeclaredField("mTabStrip");
                    mTabStripField.setAccessible(true);

                    LinearLayout mTabStrip = (LinearLayout) mTabStripField.get(tabLayout);

                    int dp10 = dip2px(10);

                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);

                        //拿到tabView的mTextView属性
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);

                        TextView mTextView = (TextView) mTextViewField.get(tabView);

                        tabView.setPadding(0, 0, 0, 0);

                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }

                        //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width;
                        params.leftMargin = dp10;
                        params.rightMargin = dp10;
                        tabView.setLayoutParams(params);

                        tabView.invalidate();
                    }

                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });

    }


    public int dip2px(float dipValue) {

        final float scale = getActivity().getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private void initFragmentList() {
        mTitleList.clear();
        for (TabBean tabBean : tabBeanList) {
            mTitleList.add(tabBean.tabName);
        }
//        mTitleList.add("大安卓");
        if (!isTotalMode) {
            mFragments.add(RecommendFragment.newInstance("推荐"));
            for (int i = 1; i < tabBeanList.size(); i++) {
                mFragments.add(TotalGoodsFragment.newInstance(tabBeanList.get(i)));
            }
        } else {
            for (int i = 0; i < tabBeanList.size(); i++) {
                mFragments.add(TotalGoodsFragment.newInstance(tabBeanList.get(i)));
            }
        }
        MyFragmentPagerAdapter myAdapter = new MyFragmentPagerAdapter(getChildFragmentManager(), mFragments, mTitleList);
        binding.vpHome.setAdapter(myAdapter);
        // 左右预加载页面的个数
        binding.vpHome.setOffscreenPageLimit(mTitleList.size() - 1);
        myAdapter.notifyDataSetChanged();
        binding.tablayoutHome.setTabMode(TabLayout.MODE_SCROLLABLE);
        reflex(binding.tablayoutHome);
        ((FragmentHomeBinding) bindingView).tablayoutHome.setupWithViewPager(binding.vpHome);
    }

    @Override
    protected void loadData() {
        if (!mIsPrepared || !mIsFirst) {
            return;
        }
        mIsFirst = false;
        ApiEntity.home();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHomeReceived(HomeTotal homeTotal) {
        data = homeTotal.getData();
        List<HomeTotal.DataBean.CategoryBean> category = data.getCategory();
        tabBeanList = new ArrayList<>();
        if (!isTotalMode) {
            tabBeanList.add(new TabBean("推荐", ""));
        }
        tabBeanList.add(new TabBean("全部商品", ""));
        for (HomeTotal.DataBean.CategoryBean categoryBean : category) {
            tabBeanList.add(new TabBean(categoryBean.getName(), categoryBean.getId() + ""));
            cateTabs.add(new CateTabAdapter.CateTab(categoryBean.getId(), categoryBean.getName()));
        }


        initFragmentList();
        EventBus.getDefault().post(data);
        initPopWindow();

    }

    private void initPopWindow() {
        View inflate = getLayoutInflater().inflate(R.layout.popwindow_total_cate, null, false);
        inflate.setBackgroundColor(Color.parseColor("#ffffff"));
        LinearLayout ll_pop = inflate.findViewById(R.id.ll_pop);
        FrameLayout fl_close=inflate.findViewById(R.id.fl_close);

        int size = cateTabs.size();
        int line = size / 3 +1;
        for (int i = 0; i < line; i++) {
            LinearLayout linearLayout = new LinearLayout(getActivity());
            for (int j = 0; j < 3; j++) {

                RadioButton radioButton = (RadioButton) getLayoutInflater().inflate(R.layout.item_cate, null, false);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.weight = 1;
                layoutParams.topMargin = dip2px(10f);
                if (j == 0 || j == 2) {
                    layoutParams.leftMargin = dip2px(30f);
                    layoutParams.rightMargin = dip2px(30f);
                } else {
                    layoutParams.leftMargin = dip2px(15f);
                    layoutParams.rightMargin = dip2px(15f);
                }

                radioButton.setLayoutParams(layoutParams);
                if (i*3+j<size) {
                    radioButton.setText(cateTabs.get(i * 3 + j).getName());
                }else{
                    radioButton.setVisibility(View.INVISIBLE);
                }
                linearLayout.addView(radioButton);
                if (i*3+j<size){
                radioButton.setTag(i * 3 + j);
                radioButtons.add(radioButton);
                }
            }
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            linearLayout.setLayoutParams(layoutParams);
            linearLayouts.add(linearLayout);
            ll_pop.addView(linearLayout);
        }
        TextView textView = new TextView(getActivity());
        textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,dip2px(20)));
        ll_pop.addView(textView);
        window = new PopupWindow();
        window.setContentView(inflate);
        ColorDrawable dw = new ColorDrawable(Color.TRANSPARENT);
        window.setBackgroundDrawable(dw);
        window.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        window.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        window.setOutsideTouchable(false);
        window.setAnimationStyle(R.style.popupwindow_anim_style);
        window.setFocusable(true);
        binding.categoryMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                window.showAsDropDown(binding.tablayoutHome);
            }
        });
        for (int i=0;i<radioButtons.size();i++){
            RadioButton radioButton = radioButtons.get(i);
            radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked){
                           resetAll();
                           buttonView.setChecked(true);
                        int tag = (int) buttonView.getTag();
                        binding.vpHome.setCurrentItem(tag+2);
                        if (window!=null&&window.isShowing()){
                            window.dismiss();
                        }
                    }
                }
            });
        }
        fl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (window!=null&&window.isShowing()){
                window.dismiss();
                }
            }
        });



    }

    private void resetAll() {
        for (int i=0;i<radioButtons.size();i++){
            radioButtons.get(i).setChecked(false);
        }
    }

    public static class TabBean {
        String tabName;
        String tabId;

        public TabBean(String tabName, String tabId) {
            this.tabName = tabName;
            this.tabId = tabId;
        }

        public String getTabName() {
            return tabName;
        }

        public void setTabName(String tabName) {
            this.tabName = tabName;
        }

        public String getTabId() {
            return tabId;
        }

        public void setTabId(String tabId) {
            this.tabId = tabId;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
//        activity.setTab_position(0);
    }

    public void setIsTotalMode() {
        this.isTotalMode = true;
    }

    public void preparePopWindow() {

    }

}
